#define  _CRT_SECURE_NO_WARNINGS
#include"List.h"

ListNode* ListCreate()
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	if (node == NULL)
	{
		perror("malloc");
		exit(1);
	}
	node->_data = -1;
	node->_prev = node;
	node->_next = node;
	return node;
}

void ListPrint(ListNode* pHead)
{
	ListNode* pcur = pHead->_next;
	while (pcur != pHead)
	{
		printf("%d -> ", pcur->_data);
		pcur = pcur->_next;
	}
	printf("\n");
}

ListNode* BuyNode(LTDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc");
		exit(1);
	}
	newnode->_data = x;
	return newnode;
}

void ListPushBack(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* newnode = BuyNode(x);
	//pHead pHead->prev newnode
	newnode->_prev = pHead->_prev;
	newnode->_next = pHead;

	pHead->_prev->_next = newnode;
	pHead->_prev = newnode;
}

bool LTEmpty(ListNode* pHead)
{
	assert(pHead);
	return pHead->_next == pHead;
}

void ListPopBack(ListNode* pHead)
{
	assert(!LTEmpty(pHead));
	ListNode* del = pHead->_prev;
	//pHead del->prev del
	del->_prev->_next = pHead;
	pHead->_prev = del->_prev;

	free(del);
	del = NULL;
}

void ListPushFront(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* newnode = BuyNode(x);
	//pHead newnode pHead->next
	newnode->_prev = pHead;
	newnode->_next = pHead->_next;

	pHead->_next = newnode;
	pHead->_next->_prev = newnode;
}

void ListPopFront(ListNode* pHead)
{
	assert(!LTEmpty(pHead));
	ListNode* del = pHead->_next;

	pHead->_next = del->_next;
	del->_next->_prev = pHead;

	free(del);
	del = NULL;
}

ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* pcur = pHead->_next;
	while (pcur != pHead)
	{
		if (pcur->_data == x)
		{
			return pcur;
		}
		pcur = pcur->_next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newnode = BuyNode(x);
	//pos->prev newnode pos
	newnode->_prev = pos->_prev;
	newnode->_next = pos;

	pos->_prev->_next = newnode;
	pos->_prev = newnode;
}

void ListErase(ListNode* pos)
{
	//pos->prev pos pos->next
	pos->_next->_prev = pos->_prev;
	pos->_prev->_next = pos->_next;

	free(pos);
	pos = NULL;
}

void ListDestory(ListNode* pHead) 
{
	ListNode* pcur = pHead->_next;
	while (pcur != pHead)
	{
		ListNode* next = pcur->_next;
		free(pcur);
		pcur = next;
	}
	free(pHead);
	pHead = NULL;
}

//void LTDesTroy(LTNode** pphead)
//{
//	LTNode* pcur = (*pphead)->next;
//	while (pcur != *pphead)
//	{
//		LTNode* next = pcur->next;
//		free(pcur);
//		pcur = next;
//	}
//	free(*pphead);
//	*pphead = NULL;
//}